<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { onMounted, reactive, ref } from 'vue'
import { PageData, SelectOption } from '@/api/common/types'
import { Delete, Lock, Plus, Search, Unlock, Edit, DataBoard } from '@element-plus/icons-vue'
import { UserCreateOrUpdate, UserDetails } from './components'
import {
  dictionaryItemName,
  dictionaryItemTag,
  getDictionarySelectOptionList
} from '@/utils/dictionary.ts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { SystemUser, SystemUserQuery, SystemUserStatusUpdate } from '@/api/system/user/types'
import {
  getDeleteSystemUserApi,
  getSystemUserDetailsApi,
  getSystemUserListApi,
  getUpdateUserStatusApi
} from '@/api/system/user'

const { t } = useI18n()
let pageData = reactive<PageData<SystemUser>>({
  total: 0,
  size: 10,
  current: 1,
  records: []
})
const getTableData = async () => {
  listLoading.value = true
  const res = await getSystemUserListApi(queryData)
  if (res) {
    pageData.records = res.data.records
    pageData.total = Number(res.data.total)
    pageData.size = Number(res.data.size)
  }
  listLoading.value = false
}

const queryData = reactive<SystemUserQuery>({
  page: 1,
  limit: 10,
  userName: '',
  mobile: '',
  userStatus: '',
  realName: ''
})

const dialogVisible = ref(false)

let userDetails = reactive<SystemUser>({})

const showDetails = async (userId: number) => {
  const res = await getSystemUserDetailsApi(userId)
  userDetails = Object.assign(userDetails, res.data)
  dialogVisible.value = true
}

const batchLockUser = async () => {
  console.log(idsSelection.value)
  if (!idsSelection.value || idsSelection.value.length <= 0) {
    ElMessage.error('至少选择一条记录进行操作')
    return
  }
  ElMessageBox.confirm(t('common.lockMessage'), t('common.lockWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      const params = ref<SystemUserStatusUpdate>({
        userIds: idsSelection.value,
        userStatus: '0'
      })
      const res = await getUpdateUserStatusApi(params.value)
      if (res.code == '200') {
        ElMessage.success('停用成功')
      } else {
        ElMessage.error('停用失败，请联系管理员')
      }
      await getTableData()
    })
    .catch(() => {})
}

const batchUnlockUser = async () => {
  console.log(idsSelection.value)
  if (!idsSelection.value || idsSelection.value.length <= 0) {
    ElMessage.error('至少选择一条记录进行操作')
    return
  }
  ElMessageBox.confirm(t('common.unlockMessage'), t('common.unlockWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      const params = ref<SystemUserStatusUpdate>({
        userIds: idsSelection.value,
        userStatus: '1'
      })
      const res = await getUpdateUserStatusApi(params.value)
      if (res.code == '200') {
        ElMessage.success('启用成功')
      } else {
        ElMessage.error('启用失败，请联系管理员')
      }
      await getTableData()
    })
    .catch(() => {})
}

const batchDeleteUser = async () => {
  console.log(idsSelection.value)
  if (!idsSelection.value || idsSelection.value.length <= 0) {
    ElMessage.error('至少选择一条记录进行操作')
    return
  }
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      const res = await getDeleteSystemUserApi(idsSelection.value.join(','))
      if (res.code == '200') {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error('删除失败，请联系管理员')
      }
      await getTableData()
    })
    .catch(() => {})
}

const lockUser = async (userId: number) => {
  ElMessageBox.confirm(t('common.lockMessage'), t('common.lockWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      const numberArray = ref([])
      numberArray.value = [userId]
      const params = ref<SystemUserStatusUpdate>({
        userIds: numberArray.value,
        userStatus: '0'
      })
      const res = await getUpdateUserStatusApi(params.value)
      if (res.code == '200') {
        ElMessage.success('停用成功')
      } else {
        ElMessage.error('停用失败，请联系管理员')
      }
      await getTableData()
    })
    .catch(() => {})
}

const unlockUser = async (userId: number) => {
  ElMessageBox.confirm(t('common.unlockMessage'), t('common.unlockWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      const numberArray = ref([])
      numberArray.value = [userId]
      const params = ref<SystemUserStatusUpdate>({
        userIds: numberArray.value,
        userStatus: '1'
      })
      const res = await getUpdateUserStatusApi(params.value)
      if (res.code == '200') {
        ElMessage.success('启用成功')
      } else {
        ElMessage.error('启用失败，请联系管理员')
      }
      await getTableData()
    })
    .catch(() => {})
}

const deleteUser = async (userId: number) => {
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      const res = await getDeleteSystemUserApi(userId + '')
      if (res.code == '200') {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error('删除失败，请联系管理员')
      }
      await getTableData()
    })
    .catch(() => {})
}

const idsSelection = ref([])

const handleSelectionChange = (users: SystemUser[]) => {
  idsSelection.value = []
  users.forEach((systemUser) => {
    if (systemUser.userId) {
      idsSelection.value.push(systemUser.userId)
    }
  })
}

const listLoading = ref(false)
onMounted(() => {
  getTableData()
})

const createOrUpdateDialogVisible = ref(false)
const systemUser = ref<SystemUser>()
const title = ref('新增用户')
const isCreate = ref(true)
const createUser = () => {
  createOrUpdateDialogVisible.value = true
  title.value = '新增用户'
  isCreate.value = true
  systemUser.value = {
    userStatus: '1',
    gender: '1',
    dataPermissionRange: '1'
  }
}
const updateUser = (user: SystemUser) => {
  createOrUpdateDialogVisible.value = true
  title.value = '编辑用户'
  isCreate.value = false
  systemUser.value = user
}
const userStatusList = ref<SelectOption[]>()
const getDictionaryList = async () => {
  userStatusList.value = getDictionarySelectOptionList('status')
}
getDictionaryList()
</script>

<template>
  <ContentWrap>
    <el-form :inline="true" :model="queryData" class="demo-form-inline">
      <el-form-item label="用户名称">
        <el-input v-model="queryData.userName" placeholder="请输入用户名称" clearable />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryData.mobile" placeholder="请输入手机号" clearable />
      </el-form-item>
      <el-form-item label="真实姓名">
        <el-input v-model="queryData.realName" placeholder="请输入真实姓名" clearable />
      </el-form-item>
      <el-form-item label="用户状态" style="width: 200px">
        <el-select v-model="queryData.userStatus" placeholder="请选择用户状态">
          <el-option label="全部" value="" />
          <el-option
            v-for="item in userStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="getTableData">
          <el-icon class="el-icon--left"><Search /></el-icon> 查询</el-button
        >
      </el-form-item>
    </el-form>
    <div>
      <el-button type="primary" plain @click="createUser" style="margin-bottom: 10px"
        ><el-icon class="el-icon--left"><Plus /></el-icon> 新增</el-button
      >

      <el-button type="warning" plain @click="batchLockUser" style="margin-bottom: 10px"
        ><el-icon class="el-icon--left"><Lock /></el-icon> 停用</el-button
      >
      <el-button type="success" plain @click="batchUnlockUser" style="margin-bottom: 10px"
        ><el-icon class="el-icon--left"><Unlock /></el-icon> 启用</el-button
      >
      <el-button type="danger" plain @click="batchDeleteUser" style="margin-bottom: 10px"
        ><el-icon class="el-icon--left"><Delete /></el-icon> 删除</el-button
      >
    </div>
    <el-table
      :data="pageData.records"
      v-loading="listLoading"
      border
      style="width: 100%"
      fit
      stripe
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" width="55" />
      <el-table-column prop="userName" align="center" label="用户名称" width="120">
        <template #default="scope">
          <el-link type="primary" @click="showDetails(scope.row.userId)">{{
            scope.row.userName
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="headSculpture" align="center" label="头像" width="100">
        <template #default="scope">
          <el-image style="width: 60px; height: 60px" :src="scope.row.headSculpture" fit="fill" />
        </template>
      </el-table-column>
      <el-table-column prop="realName" align="center" label="真实姓名" width="120" />
      <el-table-column prop="mobile" align="center" label="手机号" width="120" />
      <el-table-column prop="email" align="center" label="电子邮箱" />
      <el-table-column prop="gender" align="center" label="性别" width="100">
        <template #default="scope">
          <el-tag class="ml-2" :type="dictionaryItemTag('gender', scope.row.gender)">
            <span v-if="scope.row.gender">{{
              dictionaryItemName('gender', scope.row.gender)
            }}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="roleStatus" align="center" label="角色状态" width="100">
        <template #default="scope">
          <el-tag class="ml-2" :type="dictionaryItemTag('status', scope.row.userStatus)">
            <span v-if="scope.row.userStatus">{{
              dictionaryItemName('status', scope.row.userStatus)
            }}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" align="center" label="创建时间" width="180" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="260"
        fixed="right"
      >
        <template #default="{ row }">
          <el-link type="primary" plain @click="updateUser(row)">
            <el-icon class="el-icon--right"><Edit /></el-icon>编辑
          </el-link>
          <el-link
            v-if="row.userStatus === '1'"
            type="warning"
            style="margin-left: 5px"
            plain
            @click="lockUser(row.userId)"
            ><el-icon class="el-icon--left"><Lock /></el-icon>
            停用
          </el-link>
          <el-link
            v-if="row.userStatus === '0'"
            type="success"
            style="margin-left: 5px"
            plain
            @click="unlockUser(row.userId)"
            ><el-icon class="el-icon--left"><Unlock /></el-icon>
            启用
          </el-link>
          <el-link type="primary" style="margin-left: 5px" plain
            ><el-icon class="el-icon--left"><DataBoard /></el-icon>分配角色</el-link
          >
          <el-link type="danger" style="margin-left: 5px" plain @click="deleteUser(row.userId)"
            ><el-icon class="el-icon--left"><Delete /></el-icon>删除</el-link
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="true"
      v-model:current-page="queryData.page"
      v-model:page-size="queryData.limit"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="pageData.total"
      style="margin-top: 20px"
      v-show="pageData.total > 0"
      @size-change="getTableData"
      @current-change="getTableData"
    />
  </ContentWrap>
  <UserDetails v-if="dialogVisible" v-model="dialogVisible" :userDetails="userDetails" />
  <UserCreateOrUpdate
    v-if="createOrUpdateDialogVisible"
    v-model="createOrUpdateDialogVisible"
    :user="systemUser"
    :title="title"
    :create="isCreate"
    :refreshList="getTableData"
  />
</template>
